/**
 * @filename:SaleOrderServiceImpl Feb 18, 2025
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.QingSaleOrderDao;
import com.wonder.app.mapper.QingSaleOrderDetailDao;
import com.wonder.app.mapper.SaleOrderDao;
import com.wonder.app.mapper.SaleOrderDetailDao;
import com.wonder.app.request.QingSaleOrderRequest;
import com.wonder.app.request.SaleOrderRequest;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
//import com.wonder.utils.DateUtils;

/**   
 * @Description:TODO(销售订单服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class QingSaleOrderServiceImpl extends ServiceImpl<QingSaleOrderDao, QingSaleOrder> implements QingSaleOrderService  {

	private static final Logger _logger = LoggerFactory.getLogger(PurReturnServiceImpl.class);
	@Autowired
	private QingSaleOrderService qingSaleOrderService;
	@Autowired
	private QingSaleOrderDao qingSaleOrderDao;
	@Autowired
	private QingSyncOrderService qingSyncOrderService;
	@Autowired
	private QingSaleOrderDetailDao qingSaleOrderDetailDao;
	@Autowired
	private QingSaleOrderDetailService qingSaleOrderDetailService;
	@Autowired
	private IVtuzxKingdeeService vtuzxKingdeeService;
	@Autowired
	private SyncKingdeeOrderService syncKingdeeOrderService;



	@Autowired
	private MaterialService materialService;

	@Override
	public String validate(QingSaleOrder qingSaleOrder, String type) {
		return "";
	}

	@Override
	public IPage<QingSaleOrder> selectList(QingSaleOrderRequest request, Page<QingSaleOrder> page) {
		LambdaQueryWrapper<QingSaleOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		if (null != request.getId()) {
			lambdaQueryWrapper.eq(QingSaleOrder::getId, request.getId());
		}

		if (StringUtils.hasText(request.getCusTomer())) {
			lambdaQueryWrapper.like(QingSaleOrder::getCusTomer, request.getCusTomer());
		}

		if (!VtuzxUtil.isEmpty(request.getAccCustomer())){
			lambdaQueryWrapper.like(QingSaleOrder::getAccCustomer,request.getAccCustomer());
		}

		if (StringUtils.hasText(request.getSyncNo())) {
			lambdaQueryWrapper.like(QingSaleOrder::getSyncNo, request.getSyncNo());
		}


		if (StringUtils.hasText(request.getCusBillNo())) {
			lambdaQueryWrapper.like(QingSaleOrder::getCusBillNo, request.getCusBillNo());
		}

		if (request.getInDate() != null){
			Date[] inDate=request.getInDate();
			if(inDate.length>0)
				lambdaQueryWrapper.ge(QingSaleOrder::getInDate, inDate[0]);
			if(inDate.length==2)
				lambdaQueryWrapper.le(QingSaleOrder::getInDate,inDate[1]);

		}

		if (request.getInDate() != null) {
			Date[] fCREATEDATE = request.getInDate();
			if (fCREATEDATE.length > 0) {
				// 设置开始时间为当天的零点
				Calendar startCalendar = Calendar.getInstance();
				startCalendar.setTime(fCREATEDATE[0]);
				startCalendar.set(Calendar.HOUR_OF_DAY, 0);
				startCalendar.set(Calendar.MINUTE, 0);
				startCalendar.set(Calendar.SECOND, 0);
				startCalendar.set(Calendar.MILLISECOND, 0);
				Date startDate = startCalendar.getTime();
				lambdaQueryWrapper.ge(QingSaleOrder::getInDate, startDate);
			}
			if (fCREATEDATE.length == 2) {
				// 设置结束时间为当天的24点
				Calendar endCalendar = Calendar.getInstance();
				endCalendar.setTime(fCREATEDATE[1]);
				endCalendar.set(Calendar.HOUR_OF_DAY, 23);
				endCalendar.set(Calendar.MINUTE, 59);
				endCalendar.set(Calendar.SECOND, 59);
				endCalendar.set(Calendar.MILLISECOND, 999);
				Date endDate = endCalendar.getTime();
				lambdaQueryWrapper.le(QingSaleOrder::getInDate, endDate);
			}
		}


		if (StringUtils.hasText(request.getUser())) {
			lambdaQueryWrapper.like(QingSaleOrder::getUser, request.getUser());
		}


		lambdaQueryWrapper.orderByDesc(QingSaleOrder::getId);
		Page<QingSaleOrder> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
	}

	@Override
	public Map<String, Object> getQingSaleOrderDetail(Map<String, Object> map) {
		String billNo = map.get("billNo").toString();
		QingSaleOrder qingsaleorderform = qingSaleOrderDao.selectOne(new LambdaQueryWrapper<QingSaleOrder>()
				.eq(QingSaleOrder::getCusBillNo,billNo));
		List<QingSaleOrderDetail> qingsaleorderList = qingSaleOrderDetailDao.selectList(new LambdaQueryWrapper<QingSaleOrderDetail>()
				.eq(QingSaleOrderDetail::getCusBillNo,billNo));
		Map<String,Object> data = new HashMap<>();
		data.put("data",qingsaleorderform);
		data.put("dataList",qingsaleorderList);
		return data;
	}

	@Override
	public AjaxResult<Object> importData(String userName,Long user_id,List<Map<String,Object>> map) throws Exception {
		if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据，请检查模板sheet页"));
		Map<String,Object> orderMap = new HashMap<>();//key:客户订单号val:单据头
		Map<String,Object> detailMap = new HashMap<>();//key:客户订单号 val:单据体集合
		List<String> cusBillList = new ArrayList<>();//客户订单号集合
		try {
			Map<String, Object> headRow = map.get(0);
			String rqHd = String.valueOf(headRow.get("__EMPTY")).trim();
			String zdkhHd = String.valueOf(headRow.get("__EMPTY_1")).trim();
			String jskhHd = String.valueOf(headRow.get("__EMPTY_2")).trim();
			String bbHd = String.valueOf(headRow.get("__EMPTY_3")).trim();
			String ddhHd = String.valueOf(headRow.get("销售订单")).trim();
			String wlbmHd = String.valueOf(headRow.get("__EMPTY_4")).trim();
			String noHd = String.valueOf(headRow.get("__EMPTY_5")).trim();
			String djHd = String.valueOf(headRow.get("__EMPTY_6")).trim();
			String slHd = String.valueOf(headRow.get("__EMPTY_7")).trim();
			String zpHd = String.valueOf(headRow.get("__EMPTY_8")).trim();
			String cqHd = String.valueOf(headRow.get("__EMPTY_9")).trim();
			String cwphHd = String.valueOf(headRow.get("__EMPTY_10")).trim();
			String bzHd = String.valueOf(headRow.get("__EMPTY_11")).trim();
			// 确保第四行存在且数据长度至少为11
			if (map.get(1).size() < 11) {
				return AjaxResult.failed(MessageUtils.message("表格数据错误"));
			}
			if (!"终端客户".equals(zdkhHd) ||
					!"结算客户".equals(jskhHd) ||
					!"物料编码".equals(wlbmHd) ||
					!"数量".equals(noHd) ||
					!"客户订单号".equals(ddhHd) ||
					!"含税单价".equals(djHd) ||
					!"税率".equals(slHd) ||
					!"币别".equals(bbHd) ||
					!"是否为赠品".equals(zpHd) ||
					!"日期".equals(rqHd) ||
					!"船期".equals(cqHd) ||
					!"备注".equals(bzHd)||
					!"储位/批号".equals(cwphHd) ) {
				return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
			}

		} catch (Exception e) {
			// 捕获所有异常并返回错误信息
			return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
		}

		//前期校验excel模板数据
		Boolean aBoolean = checkQingSaleOrder(userName, user_id, map);
		if (!aBoolean){
			throw new RuntimeException("模板数据校验未通过,请查看传单日志查看具体信息");
		}
		List<String> customerNameList = new ArrayList<>();//终端客户名称集合
		List<String> acccustNameList = new ArrayList<>();//结算客户名称集合
		List<String> currencyList = new ArrayList<>();//币别名称集合
		List<String> maNoList = new ArrayList<>();//物料编码集合
		//先查询出物料和车间等信息
		for (Map<String,Object>  item:map){
			String orderNo = item.get("__EMPTY_2").toString();//制令单号
			if ("制令单号".equals(orderNo)){
				continue;
			}
			String materialNo = VtuzxUtil.getString(item,"__EMPTY_4");//物料编码
			if (!maNoList.contains(materialNo)){
				maNoList.add(materialNo);
			}

		}
		//查询出物料，币别，客户所需的金蝶编码等信息
		List<Map<String, Object>> materialByNo = materialService.getqingMaterialByNo(maNoList);
		//将查询到的物料信息转成map
		Map<String, Object> materialToMap = changeMaterialToMap(materialByNo);

		//订单同步开始
		String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"销售订单");
		for (Map<String,Object>  item:map){
			String cusBillNo = item.get("销售订单").toString();//客户订单号
			if ("客户订单号".equals(cusBillNo)){
				continue;
			}
			if(!cusBillList.contains(cusBillNo)){
				cusBillList.add(cusBillNo);
			}

			Integer times = VtuzxUtil.getInt(item,"__EMPTY");//接单日期（单据头日期）
			String customer = VtuzxUtil.getString(item,"__EMPTY_1");//终端客户
			if(!customerNameList.contains(customer)){
				customerNameList.add(customer);
			}
			String acccustomer = VtuzxUtil.getString(item,"__EMPTY_2");//结算客户
			if(!acccustNameList.contains(acccustomer)){
				acccustNameList.add(acccustomer);
			}

			String MaterialNo = VtuzxUtil.getString(item,"__EMPTY_4");//物料编码
			if(!maNoList.contains(MaterialNo)){
				maNoList.add(MaterialNo);
			}

			Double count = VtuzxUtil.getDouble(item,"__EMPTY_5");//数量
			double taxPrice = VtuzxUtil.getDouble(item,"__EMPTY_6");//含税单价
			Long taxRate; // 统一声明变量
			Boolean isGift = VtuzxUtil.getBoolean(item,"__EMPTY_8");//赠品
			if (isGift == true) {
				taxRate = (long) 0.0; // 赠品含税单价为0
			} else {
				taxRate = (long) VtuzxUtil.getDouble(item, "__EMPTY_7"); // 非赠品获取含税单价
			}

//			Long taxRate = VtuzxUtil.getLong(item,"__EMPTY_7");//税率
			Integer shipTime = VtuzxUtil.getInt(item,"__EMPTY_9");//船期
			String cwph = VtuzxUtil.getString(item,"__EMPTY_10");//储位/批号
			String note = VtuzxUtil.getString(item,"__EMPTY_11");//备注
			String cusPartNo = VtuzxUtil.getString(item,"__EMPTY_12");//客户件号
			String currency = VtuzxUtil.getString(item,"__EMPTY_3");//币别
			if (!currencyList.contains(currency)){
				currencyList.add(currency);
			}

			QingSaleOrder qingSaleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			if (null == qingSaleOrder){
				QingSaleOrder order = new QingSaleOrder();
				order.setCusBillNo(cusBillNo);//客户订单号
				order.setAccCustomer(acccustomer);//结算客户
				order.setCusTomer(customer);//终端客户
				order.setCurrency(currency);//币别
				order.setInDate(conVerDate(times));//日期
				order.setSyncNo(tbbillNo);//同步单号
				order.setNote(note);//备注
				orderMap.put(cusBillNo,order);
			}
			//map中添加详情数据
			List<QingSaleOrderDetail> orderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			if (null == orderDetailList || orderDetailList.size() == 0){
				List<QingSaleOrderDetail> orderDetails = new ArrayList<>();
				QingSaleOrderDetail detail = new QingSaleOrderDetail();
				detail.setCusBillNo(cusBillNo);
				detail.setCusPartNo(cusPartNo);
				Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,MaterialNo);
				if (!VtuzxUtil.isEmpty(materialMap)){
					detail.setMaterialNo(MaterialNo);
					detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
					detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
					detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
					detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
				}
				detail.setMaterialNo(MaterialNo);
				detail.setTaxPrice(taxPrice);
				detail.setTaxRate(taxRate);
				detail.setCwLot(cwph);
				detail.setQty(count);
				detail.setIsGift(isGift);
				detail.setShipDate(conVerDate(shipTime));
				orderDetails.add(detail);
				detailMap.put(cusBillNo,orderDetails);
			} else {
				QingSaleOrderDetail detail = new QingSaleOrderDetail();
				detail.setCusBillNo(cusBillNo);
				detail.setCusPartNo(cusPartNo);
				Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,MaterialNo);
				if (!VtuzxUtil.isEmpty(materialMap)){
					detail.setMaterialNo(MaterialNo);
					detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
					detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
					detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
					detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
				}
				detail.setTaxPrice(taxPrice);
				detail.setTaxRate(taxRate);
				detail.setQty(count);
				detail.setCwLot(cwph);
				detail.setIsGift(isGift);
				detail.setShipDate(conVerDate(shipTime));
				orderDetailList.add(detail);
				detailMap.put(cusBillNo,orderDetailList);
			}

		}
		List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();//需要保存到传单日志详情表中的数据
		Map<String, Object> customerMap = materialService.getqingCustomerName(customerNameList);
		Map<String, Object> acccusMap = materialService.getqingCustomerName(acccustNameList);
		Map<String, Object> currencyMap = materialService.getqingCurrencyNo(currencyList);

		//查询出已经保存过的销售订单
		List<String> saveOrderNoList =  selectQingSaleOrderNo(cusBillList);
		//数据库批量保存数据
		boolean saveBatch = saveBatchQingSaleOrder(orderMap,detailMap,cusBillList,saveOrderNoList);
		for (String cusBillNo: cusBillList){
			QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail.setOrderNo(cusBillNo);//客户订单号
			qingSyncOrderDetail.setBillNo(tbbillNo);
			qingSyncOrderDetail.setCreateTime(new Date());
			qingSyncOrderDetail.setUpdateTime(new Date());

			//检验当前客户订单号是否上传过
//			Boolean checkresult = checkSaleOrder(cusBillNo);
			Boolean checkresult = saveOrderNoList.contains(cusBillNo);
			if (checkresult){
				qingSyncOrderDetail.setMessage(String.format("单据编号:%s,已经导入过,不允许重复导入",cusBillNo));
				qingSyncOrderDetail.setIsSuccess(false);
				orderDetailList.add(qingSyncOrderDetail);
				continue;
			}


			QingSaleOrder qingSaleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<QingSaleOrderDetail> qingsaleOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			//数据库保存数据
//			boolean saveBatch = saveSaleOrder(saleOrder, saleOrderDetailList);
			try {
				syncKingdeeOrderService.syncQingSaleOrder(qingSaleOrder, qingsaleOrderDetailList,materialToMap,customerMap,acccusMap,currencyMap,user_id);
				qingSyncOrderDetail.setIsSuccess(true);
			} catch (Exception e){
				//捕获异常删除已经保存的数据
				deleteQingSaleOrder(qingSaleOrder,qingsaleOrderDetailList);
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage(e.getMessage());
			}
			orderDetailList.add(qingSyncOrderDetail);
		}
		Map<String, Object> data = qingSyncOrderService.endQingSyncOrder(orderDetailList,tbbillNo);
		return AjaxResult.success(data);
	}

	private void deleteQingSaleOrder (QingSaleOrder qingSaleOrder,List<QingSaleOrderDetail> detailList){
		List<Long> detailIdList = new ArrayList<>();
		for (QingSaleOrderDetail detail : detailList){
			Long id = detail.getId();
			if (!detailIdList.contains(id)){
				detailIdList.add(id);
			}
		}
		qingSaleOrderService.removeById(qingSaleOrder.getId());
		qingSaleOrderDetailService.removeBatchByIds(detailIdList);
	}
	/**
	 * 查询已经保存过的生产订单
	 * @param cusBillList
	 * @return
	 */
	private List<String> selectQingSaleOrderNo(List<String> cusBillList) {
		LambdaQueryWrapper<QingSaleOrder> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(QingSaleOrder::getCusBillNo,cusBillList);
		List<QingSaleOrder> qingsaleOrderList = qingSaleOrderDao.selectList(queryWrapper);
		List<String>  saveOrderNoList = new ArrayList<>();
		if (!VtuzxUtil.isEmpty(qingsaleOrderList)){
			for (QingSaleOrder  qingSaleOrder : qingsaleOrderList){
				String billNo = qingSaleOrder.getCusBillNo();
				if (!saveOrderNoList.contains(billNo)){
					saveOrderNoList.add(billNo);
				}
			}
		}

		return saveOrderNoList;
	}

	/**
	 * 批量保存销售订单(mysql)
	 * @param orderMap
	 * @param detailMap
	 * @return
	 */
	private boolean saveBatchQingSaleOrder(Map<String, Object> orderMap, Map<String, Object> detailMap,List<String> cusBillNoList,List<String> saveOrderNoList) {
		List<QingSaleOrder> qingsaleOrderList = new ArrayList<>();
		List<QingSaleOrderDetail> detailList = new ArrayList<>();
		for (String cusBillNo : cusBillNoList){
			if(saveOrderNoList.contains(cusBillNo)){
				continue;
			}
			QingSaleOrder qingsaleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<QingSaleOrderDetail> qingsaleOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			qingsaleOrderList.add(qingsaleOrder);
			detailList.addAll(qingsaleOrderDetailList);
		}
		boolean b = qingSaleOrderService.saveOrUpdateBatch(qingsaleOrderList);
		boolean r = qingSaleOrderDetailService.saveOrUpdateBatch(detailList);
		return b && r;

	}
	/**
	 * key;物料编码 val:物料相关信息(map)
	 * @param materialList
	 * @return
	 */
	private Map<String,Object> changeMaterialToMap(List<Map<String,Object>> materialList){
		Map<String,Object> dataMap = new HashMap<>();
		for (Map<String,Object> data : materialList){
			String FNUMBER = VtuzxUtil.getString(data,"FNUMBER");
			String FNAME = VtuzxUtil.getString(data,"FNAME");
			String FSPECIFICATION  = VtuzxUtil.getString(data,"FSPECIFICATION");
			String unitNo = VtuzxUtil.getString(data,"unitNo");//单位编码
			String unitName = VtuzxUtil.getString(data,"unitName");//单位编码
			Map<String,Object> materialMap = new HashMap<>();
			materialMap.put("FNUMBER",FNUMBER);
			materialMap.put("FNAME",FNAME);
			materialMap.put("FSPECIFICATION",FSPECIFICATION);
			materialMap.put("unitName",unitName);
			materialMap.put("unitNo",unitNo);
			dataMap.put(FNUMBER,materialMap);
		}
		return dataMap;
	}
	/**
	 * Excel日期转换
	 * @param times
	 * @return
	 */
	public Date conVerDate(int times){
		Calendar calendar = Calendar.getInstance();
		calendar.set(1900,Calendar.JANUARY,1);
		calendar.add(Calendar.DAY_OF_MONTH,times -2);
		Date date = calendar.getTime();
		return date;
	}
	@Override
	public Map<String, Object> getQingSaleOrderDelete(String userName,Long user_id,Map<String, Object> map) throws Exception {
		String cusBillNo = map.get("cusBillNo").toString();
		String cuFbillno = "";
		VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
		//根据客户订单号查询金蝶销售订单
		List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client,"SAL_SaleOrder", new VtuzxArrayList<>(
						"F_PSUH_Text_qtr",
						"FBillNo"
				),
				// 组合两个过滤条件（规格型号 + 物料分组）
				String.format("F_PSUH_Text_qtr = '%s' ",
						cusBillNo), null, 0, 0);

		if (!VtuzxUtil.isEmpty(prdcumQuery)) {
			cuFbillno = VtuzxUtil.getString(prdcumQuery.get(0),"FBillNo");
			throw new RuntimeException(String.format("该订单已存在不能删除订单号:%s 销售订单号:%s ", cusBillNo,cuFbillno));
		}
		// 删除本地数据库记录
		int deletedDetails = qingSaleOrderDetailDao.delete(
				new LambdaQueryWrapper<QingSaleOrderDetail>()
						.eq(QingSaleOrderDetail::getCusBillNo, cusBillNo)
		);

		int deletedMain = qingSaleOrderDao.delete(
				new LambdaQueryWrapper<QingSaleOrder>()
						.eq(QingSaleOrder::getCusBillNo, cusBillNo)
		);

		Map<String, Object> data = new HashMap<>();
		data.put("success", true);
		data.put("message", String.format("主表删除 %d 条，明细表删除 %d 条", deletedMain, deletedDetails));
		return data;
	}
	/**
	 * 保存销售订单的信息
	 * @param
	 * @param
	 * @return
	 */
	private Boolean saveQingSaleOrder(QingSaleOrder qingSaleOrder,List<QingSaleOrderDetail> detailList){

		boolean saveBatch = qingSaleOrderService.saveOrUpdate(qingSaleOrder);
		boolean detailBatch = qingSaleOrderDetailService.saveOrUpdateBatch(detailList);
		return saveBatch && detailBatch;
	}

	@Override
	public AjaxResult<Object> importUpdateData(String userName,Long user_id,List<Map<String, Object>> map) throws Exception {
		if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据，请检查模板sheet页"));
		Map<String,Object> orderMap = new HashMap<>();//key:客户订单号val:单据头
		Map<String,Object> detailMap = new HashMap<>();//key:客户订单号 val:单据体集合
		List<String> cusBillList = new ArrayList<>();//客户订单号集合
		String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"销售订单变更");
		try {
			Map<String, Object> headRow = map.get(0);
			String rqHd = String.valueOf(headRow.get("__EMPTY")).trim();
			String zdkhHd = String.valueOf(headRow.get("__EMPTY_1")).trim();
			String jskhHd = String.valueOf(headRow.get("__EMPTY_2")).trim();
			String bbHd = String.valueOf(headRow.get("__EMPTY_3")).trim();
			String ddhHd = String.valueOf(headRow.get("销售订单")).trim();
			String wlbmHd = String.valueOf(headRow.get("__EMPTY_4")).trim();
			String noHd = String.valueOf(headRow.get("__EMPTY_5")).trim();
			String djHd = String.valueOf(headRow.get("__EMPTY_6")).trim();
			String slHd = String.valueOf(headRow.get("__EMPTY_7")).trim();
			String zpHd = String.valueOf(headRow.get("__EMPTY_8")).trim();
			String cqHd = String.valueOf(headRow.get("__EMPTY_9")).trim();
			String cwphHd = String.valueOf(headRow.get("__EMPTY_10")).trim();
			String bzHd = String.valueOf(headRow.get("__EMPTY_11")).trim();
			String bglxHd = String.valueOf(headRow.get("__EMPTY_13")).trim();
			// 确保第四行存在且数据长度至少为11
			if (map.get(1).size() < 11) {
				return AjaxResult.failed(MessageUtils.message("表格数据错误"));
			}
			if (!"终端客户".equals(zdkhHd) ||
					!"结算客户".equals(jskhHd) ||
					!"物料编码".equals(wlbmHd) ||
					!"数量".equals(noHd) ||
					!"客户订单号".equals(ddhHd) ||
					!"含税单价".equals(djHd) ||
					!"税率".equals(slHd) ||
					!"币别".equals(bbHd) ||
					!"是否为赠品".equals(zpHd) ||
					!"日期".equals(rqHd) ||
					!"船期".equals(cqHd) ||
					!"备注".equals(bzHd) ||
			        !"变更类型".equals(bglxHd)||
					!"储位/批号".equals(cwphHd) ){
				return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
			}

		} catch (Exception e) {
			// 捕获所有异常并返回错误信息
			return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
		}

		//TODO
		List<QingSyncOrderDetail> detailList = new ArrayList<>();
		for (Map<String,Object>  item:map){

			String cusBillNo = item.get("销售订单").toString();//客户订单号
			if ("客户订单号".equals(cusBillNo)){
				continue;
			}

			if(!cusBillList.contains(cusBillNo)){
				cusBillList.add(cusBillNo);
			}
			QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail.setOrderNo(cusBillNo);//客户订单号
			qingSyncOrderDetail.setBillNo(tbbillNo);
			qingSyncOrderDetail.setCreateTime(new Date());
			qingSyncOrderDetail.setUpdateTime(new Date());


			Integer times = VtuzxUtil.getInt(item,"__EMPTY");//接单日期（单据头日期）
			String customer = VtuzxUtil.getString(item,"__EMPTY_1");//终端客户
			String acccustomer = VtuzxUtil.getString(item,"__EMPTY_2");//结算客户
			String currency = VtuzxUtil.getString(item,"__EMPTY_3");//币别
			String MaterialNo = VtuzxUtil.getString(item,"__EMPTY_4");//物料编码
			Double count = VtuzxUtil.getDouble(item,"__EMPTY_5");//数量
			double taxPrice = VtuzxUtil.getDouble(item,"__EMPTY_6");//含税单价
			Long taxRate = VtuzxUtil.getLong(item,"__EMPTY_7");//税率
			Boolean isGift = VtuzxUtil.getBoolean(item,"__EMPTY_8");//赠品
			Integer shipTime = VtuzxUtil.getInt(item,"__EMPTY_9");//船期
			String cwph = VtuzxUtil.getString(item,"__EMPTY_10");//储位/批号
			String note = VtuzxUtil.getString(item,"__EMPTY_11");//备注
			String cusPartNo = VtuzxUtil.getString(item,"__EMPTY_12");//客户件号
			String type = VtuzxUtil.getString(item,"__EMPTY_13");//类型

			//检验当前客户订单号是否上传过
			Boolean checkresult = checkQingSaleOrder(cusBillNo);
			if (!checkresult){//没有上传
				qingSyncOrderDetail.setMessage(String.format("客户订单号:%s,没有导入,无法变更",cusBillNo));
				qingSyncOrderDetail.setIsSuccess(false);
				detailList.add(qingSyncOrderDetail);
//				continue;
			} else {
				QingSaleOrder qingSaleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
				if (null == qingSaleOrder){
					QingSaleOrder order = qingSaleOrderDao.selectOne(new LambdaQueryWrapper<QingSaleOrder>()
							.eq(QingSaleOrder::getCusBillNo, cusBillNo));
					order.setCusBillNo(cusBillNo);//客户订单号
					order.setAccCustomer(acccustomer);//结算客户
					order.setCusTomer(customer);//终端客户
					order.setCurrency(currency);//币别
					order.setInDate(conVerDate(times));//日期
					order.setNote(note);//备注
					orderMap.put(cusBillNo,order);
				}
				//map中添加详情数据
				List<QingSaleOrderDetail> orderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
				if (null == orderDetailList || orderDetailList.size() == 0){//第一次向map中添加数据
					List<QingSaleOrderDetail> orderDetails = new ArrayList<>();
					//判断变更类型是新增，修改，删除新增的话数据库没有值
					if ("新增".equals(type)){//新增的话校验数据库不允许有当亲物料编码的明细
						QingSaleOrderDetail saveDetail = qingSaleOrderDetailDao.selectOne(new LambdaQueryWrapper<QingSaleOrderDetail>()
								.eq(QingSaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(QingSaleOrderDetail::getMaterialNo, MaterialNo));
						if (null != saveDetail){
							qingSyncOrderDetail.setMessage(String.format("客户订单号:%s,已经存在物料编码为:%s,无法做新增",cusBillNo,MaterialNo));
							qingSyncOrderDetail.setIsSuccess(false);
							detailList.add(qingSyncOrderDetail);
							continue;
						}
						QingSaleOrderDetail detail = new QingSaleOrderDetail();
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setMaterialNo(MaterialNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setCwLot(cwph);
						detail.setQty(count);
						detail.setIsGift(isGift);
						detail.setShipDate(conVerDate(shipTime));
						orderDetails.add(detail);
						detail.setType(type);
						detailMap.put(cusBillNo,orderDetails);

					} else {
						QingSaleOrderDetail detail = qingSaleOrderDetailDao.selectOne(new LambdaQueryWrapper<QingSaleOrderDetail>()
								.eq(QingSaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(QingSaleOrderDetail::getMaterialNo, MaterialNo));
						if (null == detail){
							qingSyncOrderDetail.setMessage(String.format("客户订单号:%s,已经存在物料编码为:%s,无法做修改或删除",cusBillNo,MaterialNo));
							qingSyncOrderDetail.setIsSuccess(false);
							detailList.add(qingSyncOrderDetail);
							continue;
						}
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setMaterialNo(MaterialNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setQty(count);
						detail.setCwLot(cwph);
						detail.setIsGift(isGift);
						detail.setShipDate(conVerDate(shipTime));
						orderDetails.add(detail);
						detail.setType(type);
						detailMap.put(cusBillNo,orderDetails);
					}

				} else {
					if ("新增".equals(type)){
						QingSaleOrderDetail saveDetail = qingSaleOrderDetailDao.selectOne(new LambdaQueryWrapper<QingSaleOrderDetail>()
								.eq(QingSaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(QingSaleOrderDetail::getMaterialNo, MaterialNo));
						if (null != saveDetail){
							qingSyncOrderDetail.setMessage(String.format("客户订单号:%s,已经存在物料编码为:%s,无法做新增",cusBillNo,MaterialNo));
							qingSyncOrderDetail.setIsSuccess(false);
							detailList.add(qingSyncOrderDetail);
							continue;

						}
						QingSaleOrderDetail detail = new QingSaleOrderDetail();
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setMaterialNo(MaterialNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setCwLot(cwph);
						detail.setQty(count);
						detail.setIsGift(isGift);
						detail.setShipDate(conVerDate(shipTime));
						detail.setType(type);
						orderDetailList.add(detail);
						detailMap.put(cusBillNo,orderDetailList);
					} else {
						QingSaleOrderDetail detail = qingSaleOrderDetailDao.selectOne(new LambdaQueryWrapper<QingSaleOrderDetail>()
								.eq(QingSaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(QingSaleOrderDetail::getMaterialNo, MaterialNo));
						if (null == detail){

							qingSyncOrderDetail.setMessage(String.format("客户订单号:%s,不存在物料编码为:%s,无法做修改或删除",cusBillNo,MaterialNo));
							qingSyncOrderDetail.setIsSuccess(false);
							detailList.add(qingSyncOrderDetail);
							continue;
						}
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setMaterialNo(MaterialNo);
						detail.setTaxPrice(taxPrice);
						detail.setCwLot(cwph);
						detail.setTaxRate(taxRate);
						detail.setQty(count);
						detail.setIsGift(isGift);
						detail.setShipDate(conVerDate(shipTime));
						detail.setType(type);
						orderDetailList.add(detail);
						detailMap.put(cusBillNo,orderDetailList);
					}

				}
			}


		}


		for (String cusBillNo: cusBillList){
			QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail = new QingSyncOrderDetail();
			qingSyncOrderDetail.setOrderNo(cusBillNo);//客户订单号
			qingSyncOrderDetail.setBillNo(tbbillNo);
			qingSyncOrderDetail.setCreateTime(new Date());
			qingSyncOrderDetail.setUpdateTime(new Date());

			QingSaleOrder qingSaleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<QingSaleOrderDetail> saleqingOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);

			try {
				if(!VtuzxUtil.isEmpty(qingSaleOrder) && !VtuzxUtil.isEmpty(saleqingOrderDetailList) ) {
					//传销售订单变更单
					syncKingdeeOrderService.syncqingSaleUpdateOrder(qingSaleOrder, saleqingOrderDetailList, user_id);
					//数据库成功保存数据
					boolean saveBatch = saveQingSaleOrder(qingSaleOrder, saleqingOrderDetailList);
					qingSyncOrderDetail.setIsSuccess(true);
				}else{
					qingSyncOrderDetail.setIsSuccess(false);
				}
			} catch (Exception e){
				//捕获异常删除已经保存的数据
//				deleteSaleOrder(saleOrder,saleOrderDetailList);
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage(e.getMessage());
			}
			if( !VtuzxUtil.isEmpty(qingSaleOrder) && !VtuzxUtil.isEmpty(saleqingOrderDetailList) ) {
				detailList.add(qingSyncOrderDetail);
			}
		}
		Map<String, Object> data = qingSyncOrderService.endQingSyncOrder(detailList,tbbillNo);
		return AjaxResult.success(data);

	}
	/**
	 * 检查是否导入过该订单
	 * @param BillNo
	 * @return
	 */
	public Boolean checkQingSaleOrder(String BillNo){
		QueryWrapper<QingSaleOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("CusBillNo",BillNo);
		QingSaleOrder qingSaleOrder = qingSaleOrderDao.selectOne(queryWrapper);
		if(qingSaleOrder != null){
			return true;
		}else {
			return false;
		}
	}
	/**
	 * 校验销售订单导入的数据
	 * @param user_id
	 * @param map
	 * @return
	 * @throws Exception
	 */
	private Boolean checkQingSaleOrder(String userName,Long user_id,List<Map<String,Object>> map) throws Exception{
		//添加行号
		int i = 3;
		for (Map<String,Object> data : map){
			data.put("line",i);
			i++;
		}
		//添加之前做一个删除
		materialService.deleteQingSaleOrder(userName,user_id);
		//sqlserver数据库添加当前导入的数据
		materialService.saveQingSaleOrder(userName,user_id,map);
		//校验客户订单号
		List<Map<String,Object>> checkQingCusBillNo =  materialService.checkQingCusBillNo(user_id);
		//校验客户
		List<Map<String,Object>> checkqingCustomer =  materialService.checkqingCustomer(user_id);
		List<Map<String,Object>> checkqingAccCustomer =  materialService.checkqingAccCustomer(user_id);
		//校验物料
		List<Map<String,Object>> checkqingMaterialNo =  materialService.checkqingMaterialNo(user_id);
		//校验数量是否都大于0
		List<Map<String,Object>> checkqingCount =  materialService.checkqingCount(user_id);
		//校验金额是否都大于0
		List<Map<String,Object>> checkqingdjCount =  materialService.checkqingdjCount(user_id);
		//校验船期
		List<Map<String,Object>> checkqingSheep =  materialService. checkqingSheep(user_id);
		//判断查询的数据如果都为空的话说明模板数据校验通过可以导入,如果不为空的话添加日志信息并且停止传单
		if (VtuzxUtil.isEmpty(checkQingCusBillNo) &&  VtuzxUtil.isEmpty(checkqingCustomer) && VtuzxUtil.isEmpty(checkqingAccCustomer)
				&& VtuzxUtil.isEmpty(checkqingMaterialNo) && VtuzxUtil.isEmpty(checkqingCount) && VtuzxUtil.isEmpty(checkqingSheep)){
			return true;
		}  else {//有一个不等于空的就说明有问题,需要向日志中添加信息
			saveOrderLog(userName,user_id,checkQingCusBillNo,checkqingCustomer,checkqingAccCustomer,checkqingMaterialNo,checkqingCount,checkqingdjCount,checkqingSheep);
			return false;
		}

	}

	/**
	 * 模板级校验添加日志信息

	 */
	private void saveOrderLog(String userName,Long user_id,List<Map<String,Object>> checkQingCusBillNo,List<Map<String,Object>> checkqingCustomer,
							  List<Map<String,Object>> checkqingAccCustomer,List<Map<String,Object>> checkqingMaterialNo,List<Map<String,Object>> checkqingCount,List<Map<String,Object>> checkqingdjCount,List<Map<String,Object>> checkqingSheep){
		String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"销售订单模板数据校验");
		List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();
		if (!VtuzxUtil.isEmpty(checkQingCusBillNo)){//客户订单号校验
			for (Map<String,Object> data : checkQingCusBillNo){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的客户订单号不允许为空");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}
		if (!VtuzxUtil.isEmpty(checkqingCustomer)){//客户校验
			for (Map<String,Object> data : checkqingCustomer){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的终端客户未审核,或者不存在,或者已禁用,请确认");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}


		if (!VtuzxUtil.isEmpty(checkqingAccCustomer)){//客户校验
			for (Map<String,Object> data : checkqingAccCustomer){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的结算客户未审核,或者不存在,或者已禁用,请确认");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}
		if (!VtuzxUtil.isEmpty(checkqingMaterialNo)){//物料校验
			for (Map<String,Object> data : checkqingMaterialNo){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的物料编码未审核,或者不存在,或者已禁用,请确认");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}
		if (!VtuzxUtil.isEmpty(checkqingCount)){//数量校验
			for (Map<String,Object> data : checkqingCount){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的数量必须大于0");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}
		if (!VtuzxUtil.isEmpty(checkqingdjCount)){//数量校验
			for (Map<String,Object> data : checkqingdjCount){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行的含税单价必须大于0");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}
		if (!VtuzxUtil.isEmpty(checkqingSheep)){//数量校验
			for (Map<String,Object> data : checkqingSheep){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
				qingSyncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				qingSyncOrderDetail.setBillNo(tbbillNo);
				qingSyncOrderDetail.setCreateTime(new Date());
				qingSyncOrderDetail.setUpdateTime(new Date());
				qingSyncOrderDetail.setIsSuccess(false);
				qingSyncOrderDetail.setMessage("第" + line + "行船期不能为空,不能小于单据日期,或者单据日期不能为空,请确认");
				orderDetailList.add(qingSyncOrderDetail);
			}
		}

		qingSyncOrderService.endQingSyncOrder(orderDetailList,tbbillNo);
	}

}